package com.tinysand.advert.index.impl;

import com.tinysand.advert.index.IndexAware;
import com.tinysand.advert.utils.CommonUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;

/**
 * Created By TINY
 * Create Time 2020/2/27
 **/
@Component
@SuppressWarnings("all")
public class InterestIndex
        implements IndexAware<String, Set<Long>> {

    // 反向索引 <itTag, unitId>
    private static Map<String, Set<Long>> itUnitMap;
    // 正向索引 <unitId, itTag>
    private static Map<Long, Set<String>> unitItMap;

    static {
        itUnitMap = new ConcurrentHashMap<>();
        unitItMap = new ConcurrentHashMap<>();
    }

    @Override
    public Set<Long> get(String key) { return itUnitMap.get(key); }

    @Override
    public void add(String key, Set<Long> value) {
        Set<Long> unitIdSet = CommonUtils.getOrCreate(
                key, itUnitMap, ConcurrentSkipListSet::new);
        unitIdSet.addAll(value);

        for (Long unitId : value) {
            Set<String> its = CommonUtils.getOrCreate(
                    unitId, unitItMap, ConcurrentSkipListSet::new);
            its.add(key);
        }
    }

    @Override
    public void update(String key, Set<Long> value) {
        // 不支持更新操作
    }

    @Override
    public void delete(String key, Set<Long> value) {
        Set<Long> unitIdSet = CommonUtils.getOrCreate(
                key, itUnitMap, ConcurrentSkipListSet::new);

        unitIdSet.removeAll(value);

        for (Long unitId : value) {
            Set<String> itTagSet = CommonUtils.getOrCreate(
                    unitId, unitItMap, ConcurrentSkipListSet::new);
            itTagSet.remove(key);
        }
    }

    /* 判断推广单元中是否包含指定兴趣约束 */
    public boolean match(Long unitId, List<String> itTags) {
        // 存在 unitId 对应的推广单元并且推广单元中包含的关键字不为空
        if (unitItMap.containsKey(unitId)
                && CollectionUtils.isNotEmpty(unitItMap.get(unitId))) {
            Set<String> unitKeywords = unitItMap.get(unitId);

            return CollectionUtils.isSubCollection(itTags, unitKeywords);
        }
        return false;
    }
}
